/**
 * Copyright (C) 2013 Oleg Anastassov <oleg.anastassov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.loc.business.export;

import kz.kstu.loc.entity.Item;
import kz.kstu.loc.util.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * Date: 01.17.2013
 * Time: 14:06
 *
 * @author Oleg Anastassov
 */
public class ExcelExporter {

    private static final int KEY_COLUMN = 0;
    private static final int RUS_COLUMN = 1;
    private static final int KAZ_COLUMN = 2;

    private final File exportFile;
    private final List<Item> items;
    private String sheetName;

    private ExcelExporter(File exportFile, List<Item> items) {
        this.exportFile = exportFile;
        this.items = items;
    }

    public ExcelExporter(File exportFile, List<Item> items, String sheetName) {
        this(exportFile, items);
        this.sheetName = sheetName;
    }

    public void export() {
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet(createSheetName());

        // шрифт
        Font boldFont = wb.createFont();
        boldFont.setBoldweight(Font.BOLDWEIGHT_BOLD);

        // стиль заголовка
        CellStyle headerStyle = wb.createCellStyle();
        headerStyle.setFont(boldFont);
        headerStyle.setFillForegroundColor(new HSSFColor.GREY_25_PERCENT().getIndex());
        headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        headerStyle.setBorderBottom(CellStyle.BORDER_THIN);
        headerStyle.setBorderTop(CellStyle.BORDER_THIN);
        headerStyle.setBorderRight(CellStyle.BORDER_THIN);
        headerStyle.setBorderLeft(CellStyle.BORDER_THIN);

        // стиль обычной ячейки
        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);

        // заголовок
        Row r = sheet.createRow(0);
        Cell keyHeader = r.createCell(KEY_COLUMN);
        keyHeader.setCellValue("Ключ");
        keyHeader.setCellStyle(headerStyle);
        Cell rusHeader = r.createCell(RUS_COLUMN);
        rusHeader.setCellValue("Наименование на русском");
        rusHeader.setCellStyle(headerStyle);
        Cell kazHeader = r.createCell(KAZ_COLUMN);
        kazHeader.setCellValue("Наименование на казахском");
        kazHeader.setCellStyle(headerStyle);

        Collections.sort(items, new Comparator<Item>() {
            @Override
            public int compare(Item it1, Item it2) {
                return it1.getKey().compareToIgnoreCase(it2.getKey());
            }
        });

        // содержимое
        int rowNo = 1;
        for (Item item : items) {
            Row row = sheet.createRow(rowNo);
            Cell keyCell = row.createCell(KEY_COLUMN);
            keyCell.setCellValue(item.getKey());
            keyCell.setCellStyle(cellStyle);

            Cell rusCell = row.createCell(RUS_COLUMN);
            rusCell.setCellValue(item.getValueRus());
            rusCell.setCellStyle(cellStyle);

            Cell kazCell = row.createCell(KAZ_COLUMN);
            kazCell.setCellValue(item.getValueKaz());
            kazCell.setCellStyle(cellStyle);
            rowNo++;
        }

        // дата создания
        Row lastRow = sheet.createRow(++rowNo);
        lastRow.createCell(KEY_COLUMN).setCellValue(
                "Создан: " + new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(new Date())
        );

        // автоматически подгоняется размер колонок
        sheet.autoSizeColumn(KEY_COLUMN);
        sheet.autoSizeColumn(RUS_COLUMN);
        sheet.autoSizeColumn(KAZ_COLUMN);

        try {
            FileOutputStream fileOut = new FileOutputStream(exportFile);
            wb.write(fileOut);
            fileOut.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private String createSheetName() {
        if (!StringUtils.isEmptyOrNull(sheetName)) {
            return sheetName;
        }
        return "<unknown sheet>";
    }

}
